package com.google.code.chaotic.ejb;

import java.lang.management.ManagementFactory;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.sun.appserv.server.LifecycleEvent;
import com.sun.appserv.server.LifecycleListener;
import com.sun.appserv.server.ServerLifecycleException;

//

public class BackTierEjbLifecycleListener implements LifecycleListener {

	private static final Logger logger = Logger //
			.getLogger(BackTierEjbLifecycleListener.class.getName());

	//

	private final String ANALYSIS_TIMER_NAME = //
	AnalysisTimer.class.getPackage().getName() + ":"//
			+ "type=" + AnalysisTimer.class.getSimpleName();

	//

	@Override
	public void handleEvent(LifecycleEvent event)
			throws ServerLifecycleException {

		int eventType = event.getEventType();
		String simpleClassName = AnalysisTimer.class.getSimpleName();

		try {
			ObjectName objName = new ObjectName(ANALYSIS_TIMER_NAME);
			InitialContext ctx = event.getLifecycleEventContext()
					.getInitialContext();

			if (eventType == LifecycleEvent.READY_EVENT) {
				logger.info("Perparing to register " + simpleClassName
						+ " for management...");

				MBeanServer mbs = retrieveMBeanServer(ctx);

				// com.google.code.chaotic.ejb.AnalysisTimerLocal timerMBean
				Object timerMBean = ctx
						.lookup("java:global/backTier/backTierEJB/AnalysisTimer"
								+ "!com.google.code.chaotic.ejb.AnalysisTimerLocal");
				mbs.registerMBean(timerMBean, objName);
				logger.info(simpleClassName
						+ " was successfully registered as: "
						+ ANALYSIS_TIMER_NAME);

			} else if (eventType == LifecycleEvent.SHUTDOWN_EVENT) {
				logger.info("Perparing to unregister " + simpleClassName
						+ " for management...");

				MBeanServer mbs = retrieveMBeanServer(ctx);
				if (mbs.isRegistered(objName)) {
					mbs.unregisterMBean(objName);
					logger.info(ANALYSIS_TIMER_NAME
							+ " was successfully unregistered.");
				}
			}

		} catch (MalformedObjectNameException e) {
			logger.log(Level.SEVERE, e.toString(), e);

		} catch (NullPointerException e) {
			logger.log(Level.SEVERE, e.toString(), e);

		} catch (InstanceAlreadyExistsException e) {
			logger.log(Level.SEVERE, e.toString(), e);

		} catch (MBeanRegistrationException e) {
			logger.log(Level.SEVERE, e.toString(), e);

		} catch (NotCompliantMBeanException e) {
			logger.log(Level.SEVERE, e.toString(), e);

		} catch (Throwable e) {
			logger.log(Level.SEVERE, e.toString(), e);
		}
	}

	private MBeanServer retrieveMBeanServer(InitialContext ctx)
			throws NamingException {

		MBeanServer mbs = null;
		try {
			mbs = (MBeanServer) ctx
					.lookup("service:jmx:rmi://localhost:8686/jndi/rmi://localhost:8686/jmxrmi");

		} catch (Throwable t) {
			logger.log(Level.SEVERE, t.toString(), t);
		}
		if (mbs == null) {
			mbs = ManagementFactory.getPlatformMBeanServer();
		}
		logger.info("MBeanServer retrieved: " + mbs);
		return mbs;
	}
}
